#include <stdio.h>
#include <unistd.h>
#include <pthread.h>

#define THREADNUM 2

pthread_mutex_t g_lock;
pthread_mutex_t g_lock1;
pthread_mutex_t g_lock2;
int g_val;


//死锁
void* buyTicket(void* arg)
{
    while (1)
    {
        // 即将访问临界资源，加锁
        pthread_mutex_lock(&g_lock);

        if (g_val > 0)
        {
            printf("%p:have ticket %d\n", pthread_self(), g_val);
            g_val--;
        }
        else
        {
            break;
        }
    }

    return NULL;
}

void* MyThreadStartA(void* arg)
{
    pthread_mutex_lock(&g_lock1);
    sleep(3);
    pthread_mutex_lock(&g_lock2);

    return NULL;
}

void* MyThreadStartB(void* arg)
{
    pthread_mutex_lock(&g_lock2);
    sleep(3);
    pthread_mutex_lock(&g_lock1);

    return NULL;
}


int main()
{
    // 初始化互斥锁
    pthread_mutex_init(&g_lock, NULL);

    pthread_t tid[THREADNUM];
    for (int i = 0; i < THREADNUM; i++)
    {
        int ret = pthread_create(&tid[i], NULL, buyTicket, NULL);
        if (ret < 0)
        {
            perror("pthread_create");
            return 0;
        }
    }

    for (int i = 0; i < THREADNUM; i++)
    {
        pthread_join(tid[i], NULL);
    }


    // 销毁互斥锁
    pthread_mutex_destroy(&g_lock);
    pthread_mutex_destroy(&g_lock1);
    pthread_mutex_destroy(&g_lock2);

    return 0;
}